import React, {useEffect, useState} from 'react';
import { View, Text, Modal, TouchableOpacity, StyleSheet } from 'react-native';
import { Picker } from '@react-native-picker/picker';
import { addDays, format, getDay } from 'date-fns';
import {useRouter} from "expo-router";

const currentDate = new Date();
// 阿拉伯数字与中文的映射
const weekDayMap = ['日', '一', '二', '三', '四', '五', '六'];

const MultiColumnPickerModal = ({ visible, onConfirm, onCancel, options, startValue, endValue }) => {
    const [startYear, setStartYear] = useState(format(addDays(currentDate, 1), `MM月dd日 周${weekDayMap[getDay(addDays(currentDate, 1))]}`));
    const [startMonth, setStartMonth] = useState("00");
    const [startDay, setStartDay] = useState("00");
    const [endYear, setEndYear] = useState("00");
    const [endMonth, setEndMonth] = useState("00");
    const [endDay, setEndDay] = useState("00");
    const [nextFlag, setNextFlag] = useState(false);

    const [startYearsList, setStartYearsList] = useState([]);
    const [startMonthsList, setStartMonthsList] = useState([])
    const [startDaysList, setStartDaysList] = useState([])

    const [endYearsList, setEndYearsList] = useState([]);
    const [endMonthsList, setEndMonthsList] = useState([])
    const [endDaysList, setEndDaysList] = useState([])


    useEffect(() => {
        console.log('startValue', startValue);
        if (startValue) {
            setStartYear(format(startValue, `MM月dd日 周${weekDayMap[getDay(startValue)]}`));
            setStartMonth(format(startValue, `HH`));
            setStartDay(format(startValue, "mm"));
        };

        if (endValue) {
            setEndYear(format(startValue, `MM月dd日 周${weekDayMap[getDay(startValue)]}`));
            setEndMonth(format(startValue, `HH`));
            setEndDay(format(startValue, "mm"));
        };
    }, [startValue, endValue, visible])





    useEffect(() => {
        const startYearsLists = Array.from({ length: 120 }, (_: any, i: number) => {
            const futureDate = addDays(currentDate, i + 1);
            const it = {
                label: format(futureDate, `MM月dd日 周${weekDayMap[getDay(futureDate)]}`),
                value: format(futureDate, `MM月dd日 周${weekDayMap[getDay(futureDate)]}`),
                timeStamp: futureDate.getTime(),
            };
            return it
        });
        const startMonthsLists = Array.from({ length: 24 }, (_: any, i: number) => {
            if (i < 10) {
                return `0${i}`
            } else {
                return `${i}`;
            };
        });
        const startDaysLists = Array.from({ length: 60 }, (_, i) => {
            if (i < 10) {
                return `0${i}`
            } else {
                return `${i}`;
            };
        });

        const endYearsLists = Array.from({ length: 120 }, (_: any, i: number) => {
            const futureDate = addDays(currentDate, i + 1);
            const it = {
                label: format(futureDate, `MM月dd日 周${weekDayMap[getDay(futureDate)]}`),
                value: format(futureDate, `MM月dd日 周${weekDayMap[getDay(futureDate)]}`),
                timeStamp: futureDate.getTime(),
            };
            return it
        });
        const endMonthsLists = Array.from({ length: 24 }, (_, i) => {
            if (i < 10) {
                return `0${i}`
            } else {
                return `${i}`;
            };
        });
        const endDaysLists = Array.from({ length: 60 }, (_, i) => {
            if (i < 10) {
                return `0${i}`
            } else {
                return `${i}`;
            };
        });

        setStartYearsList(startYearsLists)
        setStartMonthsList(startMonthsLists)
        setStartDaysList(startDaysLists)
        setEndYearsList(endYearsLists)
        setEndMonthsList(endMonthsLists)
        setEndDaysList(endDaysLists)
    }, []);



    useEffect(() => {
        if (visible) {
            setNextFlag(false);
        };
    }, [visible])

    useEffect(() => {
        const list = [];
        if (nextFlag) {
            const endYearsLists = Array.from({ length: 120 }, (_, i) => {
                const futureDate = addDays(currentDate, i + 1);
                const it = {
                    label: format(futureDate, `MM月dd日 周${weekDayMap[getDay(futureDate)]}`),
                    value: format(futureDate, `MM月dd日 周${weekDayMap[getDay(futureDate)]}`),
                    timeStamp: futureDate.getTime(),
                };
                return it
            });

            const index = endYearsLists.findIndex((item) => item?.value === startYear);
            if (index !== -1) {
                endYearsLists.forEach((item, idx) => {
                    if (index <= idx) {
                        list.push(item);
                    };
                })
                console.log('startYear', startYear);
                setEndYearsList(list);
                setEndYear(startYear);
                setEndMonth(startMonth);
                setEndDay(startDay);
            };
        };
    }, [nextFlag])

    return (
        <Modal
            transparent={true}
            visible={visible}
            animationType="slide"
            onRequestClose={onCancel}
        >
            <View style={styles.modalContainer}>
                <View style={styles.pickerContainer}>
                    <View style={styles.buttonContainer}>
                        {
                            !nextFlag && (
                                <TouchableOpacity onPress={onCancel}>
                                    <Text style={styles.cancelButton}>取消</Text>
                                </TouchableOpacity>
                            )
                        }
                        {
                            nextFlag && (
                                <TouchableOpacity onPress={() => setNextFlag(false)}>
                                    <Text style={styles.cancelButton}>上一步</Text>
                                </TouchableOpacity>
                            )
                        }
                        {
                            !nextFlag && (
                                <View>
                                    <Text>开始时间</Text>
                                </View>
                            )
                        }
                        {
                            nextFlag && (
                                <View>
                                    <Text>结束时间</Text>
                                </View>
                            )
                        }
                        {
                            !nextFlag && (
                                <TouchableOpacity
                                    onPress={() => setNextFlag(true) }
                                >
                                    <Text style={styles.confirmButton}>下一步</Text>
                                </TouchableOpacity>
                            )
                        }

                        {
                            nextFlag && (
                                <TouchableOpacity
                                    onPress={() => {
                                        const futureDate = addDays(currentDate, 1);
                                        const dateCur = format(futureDate, `MM月dd日 周${weekDayMap[getDay(futureDate)]}`);
                                        const time = `${ typeof startYear  == 'string' ? startYear : dateCur} ${startMonth}:${startDay} - ${endYear} ${endMonth}:${startDay}`;
                                        let startTime = null;
                                        let endTime = null;
                                        console.log('startYear', startYear);
                                        console.log('dateCur', dateCur);
                                        console.log('endYear', endYear);

                                        startYearsList.forEach((item: any, index: any) => {
                                            // console.log('item',item)
                                            if (startYear === format(item.timeStamp, `MM月dd日 周${weekDayMap[getDay(item.timeStamp)]}`)) {
                                                // console.log('item', item);
                                                startTime = item;
                                            };
                                        });

                                        endYearsList.forEach((item: any, index: any) => {
                                            if (endYear === format(item.timeStamp, `MM月dd日 周${weekDayMap[getDay(item.timeStamp)]}`)) {
                                                console.log('item', item);
                                                endTime = item;
                                            };
                                        });

                                        if (!startTime && !endTime) {
                                            startTime = startYearsList[0];
                                            endTime = endYearsList[0]
                                        };

                                        console.log('startTime', startTime);
                                        console.log('endTime', endTime);
                                        // console.log('aaa', `${format(startTime, "yyyy-MM-dd")} ${startMonth}:${startDay}:00`);

                                        onCancel();
                                        onConfirm(time, `${format(startTime?.timeStamp, "yyyy-MM-dd")} ${startMonth}:${startDay}:00`, `${format(endTime?.timeStamp, "yyyy-MM-dd")} ${endMonth}:${endDay}:00`);
                                    }}
                                >
                                    <Text style={styles.confirmButton}>确定</Text>
                                </TouchableOpacity>
                            )
                        }
                    </View>

                    {/* 三列选择器，每列的选中项形成一个整体的激活样式 */}
                    {
                        !nextFlag && (
                            <View style={styles.pickerRow}>
                                <View style={{ width: 182, }}>
                                    <Picker
                                        selectedValue={startYear}
                                        onValueChange={(itemValue) =>  setStartYear(itemValue)}
                                        style={styles.pickerColumn}
                                        itemStyle={styles.pickerItem}
                                    >
                                        {
                                            startYearsList.map((year) => (
                                                <Picker.Item key={startYear} label={year.label} value={year.value} style={{ backgroundColor: "rgba(0,0,0,0)", paddingHorizontal: 0}}  />
                                            ))
                                        }
                                    </Picker>
                                </View>
                                <Picker
                                    selectedValue={startMonth}
                                    onValueChange={(itemValue) => setStartMonth(itemValue)}
                                    style={styles.pickerColumn}
                                    itemStyle={styles.pickerItem}
                                >
                                    {
                                        startMonthsList.map((month) => (
                                            <Picker.Item key={startMonth} label={month} value={month}  style={{ fontSize: 12, }} />
                                        ))
                                    }
                                </Picker>

                                <Picker
                                    selectedValue={startDay}
                                    onValueChange={(itemValue) => setStartDay(itemValue)}
                                    style={styles.pickerColumn}
                                    itemStyle={styles.pickerItem}
                                >
                                    {
                                        startDaysList.map((day) => (
                                            <Picker.Item key={day} label={day} value={day} style={{ fontSize: 12, }} />
                                        ))
                                    }
                                </Picker>
                            </View>
                        )
                    }


                    {
                        nextFlag && (
                            <View style={styles.pickerRow}>
                                <View style={{ width: 182, }}>
                                    <Picker
                                        selectedValue={endYear}
                                        onValueChange={(itemValue) =>{
                                            setEndYear(itemValue)
                                        }}
                                        style={styles.pickerColumn}
                                        itemStyle={styles.pickerItem}
                                    >
                                        {
                                            endYearsList.map((year) => (
                                                <Picker.Item key={year} label={year.label} value={year.value} style={{ backgroundColor: "rgba(0,0,0,0)", paddingHorizontal: 0}}  />
                                            ))
                                        }
                                    </Picker>
                                </View>
                                <Picker
                                    selectedValue={endMonth}
                                    onValueChange={(itemValue) => {
                                        if (startYear == endYear) {
                                            if (Number(startMonth) > Number(itemValue)) {
                                                console.log('hello', Number(startMonth));
                                                console.log('Number(itemValue)', Number(itemValue));
                                                return;
                                            } else {
                                                setEndMonth(itemValue);
                                            };
                                        } else {
                                            setEndMonth(itemValue);
                                        };
                                    }}
                                    style={styles.pickerColumn}
                                    itemStyle={styles.pickerItem}
                                >
                                    {
                                        endMonthsList.map((month) => (
                                            <Picker.Item key={month} label={month} value={month}  style={{ fontSize: 12, }} />
                                        ))
                                    }
                                </Picker>

                                <Picker
                                    selectedValue={endDay}
                                    onValueChange={(itemValue) => {
                                        if (startYear == endYear) {
                                            if (Number(startMonth) > Number(endMonth)) {
                                                return;
                                            } else {
                                                if (Number(endDay) > Number(itemValue)) {
                                                    return;
                                                } else {
                                                    setEndDay(itemValue);
                                                };
                                            };
                                        } else {
                                            setEndDay(itemValue);
                                        };
                                    }}
                                    style={styles.pickerColumn}
                                    itemStyle={styles.pickerItem}
                                >
                                    {
                                        endDaysList.map((day) => (
                                            <Picker.Item key={day} label={day} value={day} style={{ fontSize: 12, }} />
                                        ))
                                    }
                                </Picker>
                            </View>
                        )
                    }
                    {/* 激活项的合成区域样式 */}
                    <View style={styles.activeOverlay}></View>
                </View>
            </View>
        </Modal>
    );
};

export default MultiColumnPickerModal;

const styles = StyleSheet.create({
    modalContainer: {
        flex: 1,
        justifyContent: 'flex-end',
        backgroundColor: 'rgba(0,0,0,0.5)',
    },
    pickerContainer: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
        paddingHorizontal: 20,
        paddingTop: 12,
    },
    buttonContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 10,
    },
    cancelButton: {
        color: '#333',
        fontSize: 14,
    },
    confirmButton: {
        color: '#EC6138',
        fontSize: 14,
    },
    pickerRow: {
        flexDirection: 'row',
        // justifyContent: 'space-between',
        position: 'relative',
    },
    pickerColumn: {
        flex: 1,
    },
    pickerItem: {
        fontSize: 18,
        height: 200,
        backgroundColor: "rgba(0,0,0,0)"
    },
    activeOverlay: {
        position: 'absolute',
        top: '50%',
        left: 0,
        right: 0,
        height: 40,
        // backgroundColor: 'rgba(234,234,236, 1)',
        // transform: [{ translateY: -20 }],
        borderRadius: 10,
        zIndex: -1,
    },
});
